<?php

namespace Service;

use Core\Di;
use Core\Exception;

/**
 * AppToken服务类
 * Class TokenService
 * @package Service
 */
class AppTokenService
{
    /**
     * 生成token
     * @param $userId
     * @return string
     */
    public static function create($userId)
    {
        $params = [
            "iss" => "https://m.mutouyun.cn",
            "aud" => $userId,
            "exp" => strtotime('+1 week'),
//            "exp" => time()+60,
            "iat" => time(),
        ];
        $secretKey = Di::get('config')['secretKey'];
        $token = JwtService::encode($params, $secretKey['jwtPrivateKey'], 'RS256');
        return $token;
    }

    /**
     * 通过token获取payload
     * @return array|bool
     * @throws ;
     */
    public static function getPayloadByToken($token)
    {
        if(!empty($token)){
            $secretKey = Di::get('config')['secretKey'];
            try{
                $payload = JwtService::decode($token, $secretKey['jwtPublicKey'], ['RS256']);
                $payload = (array)$payload;
                if (is_array($payload) AND !empty($payload)) {
                    return $payload;
                }
            }catch(\Exception $e){
                return false;
            }
        }
        return false;

    }



}